package main

import (
	"fmt"
	"time"
)

func main() {

	//、

	//ch1 := make(chan int)
	//defer close(ch1)
	//done := make(chan bool)
	//defer close(done)
	//go func() {
	//	fmt.Println("subGoroutine ----")
	//	time.Sleep(3 * time.Second)
	//	data := <-ch1
	//	fmt.Println("data:", data)
	//	done <- true
	//}()
	//
	//time.Sleep(5 * time.Second)
	//ch1 <- 100
	////
	//<-done
	//fmt.Println("main over")
	//test_range()

	//c := make(chan int)
	//quit := make(chan int)
	//go func() {
	//	for i := 0; i < 10; i++ {
	//		fmt.Println(<-c)
	//	}
	//	quit <- 0
	//}()
	//
	//fibonacci(c, quit)

	//test_timeout()

	done := make(chan bool, 1)
	go worker(done)
	<-done
}

func worker(done chan bool) {
	time.Sleep(time.Hour)
	done <- true
}

func test_timeout() {
	c1 := make(chan string, 1)
	go func() {
		time.Sleep(time.Second * 2)
		c1 <- "result 1"
	}()

	select {
	case res := <-c1:
		fmt.Println(res)
	case <-time.After(time.Second * 1):
		fmt.Println("timeout 1")

	}
}
func fibonacci(c, quit chan int) {
	x, y := 0, 1
	for {
		select {
		case c <- x:
			x, y = y, x+y
		case <-quit:
			fmt.Println("quit")
			return
		}

	}
}

func test_range() {
	go func() {
		time.Sleep(1 * time.Hour)
	}()
	c := make(chan int)
	go func() {
		for i := 0; i < 10; i++ {
			c <- i
		}
		//close(c)
	}()
	for i := range c {
		fmt.Println(i)
	}
	fmt.Println("finished")
}

func calcSquares(number int, squareop chan int) {
	sum := 0
	for number != 0 {
		digit := number % 10
		sum += digit * digit
		number /= 10
	}
	squareop <- sum
}
